package org.ainlolcat.ainscience.entity.links;

import org.ainlolcat.Variable;
import org.ainlolcat.aincalc2.MissingDependenciesException;
import org.ainlolcat.ainscience.Controller;
import org.ainlolcat.ainscience.column.Column;
import org.ainlolcat.ainscience.entity.Entity;
import org.ainlolcat.ainscience.matrix.MatrixFileParser;

/**
 * @author ainlolcat
 * Date: 11/10/11
 */
public class NearestLink extends EqualLink {


    public NearestLink(String name, Integer columnID, String l2entity, Integer l2column, String type) {
        super(name, columnID, l2entity, l2column, type);
    }

    public Variable getValue(Integer columnId, Integer rowNum) {
        Entity linked = Controller.getInstance().getProject().getEntityByName(l2entity);
        if (linked == null)
            throw new MissingDependenciesException(l2entity);
        Entity home = this.entity;
        Column c1 = home.getColumnById(this.columnID);
        Column c2 = linked.getColumnById(this.l2column);
        Column c3 = linked.getColumnById(columnId);
        if ( c1!=null && c2!=null){
            double[] indexesC2 = c2.getDoubleRepresentation();  //assume nearest supports only numeric implementation
            double goal = c1.getCanonicalValue(rowNum).getDoubleValue();;
            int index = 0;
            for (int i=0;i<indexesC2.length;i++){
                if (Math.abs(goal - indexesC2[i]) < Math.abs(goal - indexesC2[index]))
                    index = i;
            }
            return c3.getCanonicalValue(index);
        }
        throw new IllegalArgumentException("Indexes null");
    }
}
